package proj.pt.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import proj.pt.model.Course;
import proj.pt.model.SubCourse;
import proj.pt.model.Subject;
import proj.pt.model.User;

public class SubjectController extends CustomSimpleFormController {

	protected Object formBackingObject(HttpServletRequest request)
    throws Exception{
		// getting the id from the request, if it is supplied as parameter.
		// else -1 will be set.
		long id = ServletRequestUtils.getLongParameter(request, "id", -1);
		
		// if id value is greater than -1, then requesting to lead an already existing from database,
		// else create a new object.
		Subject subject = null;
		if(id > -1){
			// load from database
			subject = getLogicProcessor().getSubject(new Long(id));
		} //end if
		
		// there may be chance that false id has given for loading from database, and that is not present there, so  will be null;
		if(subject == null)
		return new Subject();
		else return subject;
	}
	
	protected Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception {
		Map dataMap = super.referenceData(request, command, errors);
		
		Subject subject = (Subject)command;
		
		String action = WebUtils.getAction(request);
		
		if("action_course_select".equals(action)){
			// course selected, so load batches and semesters according to that.
			dataMap.put("semesters", getLogicProcessor().getSubCourses(subject.getCourse()));
			
		} else if(subject.getSubCourse() != null){
			// semester already available as selected, so retain the batches and semester list
			// as per this selection.
			if(subject.getSubCourse().getCourse() != null)
				subject.setCourse(getLogicProcessor().getCourse(subject.getSubCourse().getCourse().getId()));
			
			dataMap.put("semesters", getLogicProcessor().getSubCourses(subject.getSubCourse().getCourse()));
			
		} //end else if
		
		User currentUser = (User)dataMap.get("currentUser");
		dataMap.put("courses", getLogicProcessor().getCourses(currentUser));
		
		return dataMap;
	} //end referenceData
	
	
	
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(SubCourse.class, "subCourse", new SubCourseEditor(getLogicProcessor()));
		binder.registerCustomEditor(Course.class, "course", new CourseEditor(getLogicProcessor()));
	}
	
	
	
	/**
	 * This method does the validation.
	 */
	protected void onBindAndValidate(HttpServletRequest request,
            Object command,
            BindException errors) throws Exception {
		
		// if no validation required, then just return from this method.
		if(!doValidate(request))return;
		
				
		Subject subject = (Subject)command;
		
		if(!StringUtils.hasLength(subject.getName())){
			errors.reject("subjectName.required", "Subject Name required.");
		} //end if
		
		
		// look for subject Id 
		if(!StringUtils.hasLength(subject.getCode())){
			errors.reject("subjectCode.required", "Subject Code required.");
		} else {
			// look for Subject code already exist or not.
			if(!getLogicProcessor().validateSubjectCode(subject)){
				errors.reject("subjectCode.exist", "Subject code exists, please enter a unique Code.");
			} //end if
		}
		
		if(subject.getSubCourse() == null){
			errors.reject("semester.required", "Please select a Semester.");
		} //end if
		
						
	}
	
	
	protected ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response,
            Object command,
            BindException errors)      throws Exception {
		
		String action = WebUtils.getAction(request);
		
		if("action_save".equals(action)){
			getLogicProcessor().saveOrUpdateSubject((Subject)command);
		} else if("action_delete".equals(action)){
			getLogicProcessor().deleteSubject((Subject)command);
		} else if("action_cancel".equals(action)){
			// do nothing
		} else{
			// do nothing.
		} 
		
				
		ModelAndView  mav = new ModelAndView();
		mav.setView(new RedirectView(getSuccessURI()));
		return mav;
	} //end onSubmit	
	
}
